﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

using HK2009.Common;
using HK2009.BusinessFacade;
using HK2009.BusinessFacadeHandler;
using HK2009.EntityQuery;
using System.Data.SqlClient;
using System.Text;
using System.Threading;
using System.Text.RegularExpressions;

public partial class BookingManage_PendingList : BasePage
{
    IBNBookingHandler bookingManager = new BNBookingHandler();
    DataBase db = new DataBase();
    string language = "";

    protected void Page_Load(object sender, EventArgs e)
    {
        language = Thread.CurrentThread.CurrentUICulture.ToString().ToLower();
        
        if (!IsPostBack)
        {
            if (Session["UserID"] != null)
            {
                ISystemHandler sysManage = new SystemHandler();
                string strPermission = sysManage.GetLoginUserPermissions();
                bool isCpmRole2 = sysManage.IsCompanyRoles2();
                if ("0".Equals(Session["LoginUserClientID"].ToString()) || isCpmRole2 == true)
                {
                    Response.Redirect("../BookingManage/PendingListForCpm.aspx");
                }
                
                if (!strPermission.Contains("1046"))
                {
                    Response.Redirect("~/NotPurview.aspx");
                    return;
                }
                else
                {
                    //判断用户有没有Send Booking权限
                    if (strPermission.Contains("1047"))
                    {
                        btnSave.Visible = true;
                    }
                    else
                    {
                        btnSave.Visible = false;
                    }
                }

               // CheckPagePermission();//判断当前用户有没有添加删除更新的权限

            }
           
            ViewState["OrderBy"] = "PKID";
            ViewState["Accending"] = "asc";
            dataBind();
            initSearchBox();
        }
    }

    private void initSearchBox()
    {
        fillShipper();
        fillWhouse();
    }

    private void fillShipper()
    {
        ISyClientHandler clientManager = new SyClientHandler();

        DataTable dt = clientManager.GetClientListByTypeID(int.Parse(Enums.CT.TYR.ToString("d")));
        lstShipper.DataSource = dt;

        if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("en"))
        {
            lstShipper.DataTextField = "ENGShortName";
        }
        else if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("zh-hk"))
        {
            lstShipper.DataTextField = "HKShortName";
        }
        else
        {
            lstShipper.DataTextField = "CNShortName";
        }
        lstShipper.DataValueField = "PKID";
        lstShipper.DataBind();

    }

    private void fillWhouse()
    {
        ISyClientHandler clientManager = new SyClientHandler();
        string sqlStr = "SELECT DISTINCT client.* FROM Sy_Client client " +
                        " inner join Sy_ClientType type on client.PKID = type.ClientID " +
                        " inner join Sy_Code code on type.SyCodeID = code.PKID" +
                        " where code.Type='CT' and (code.Code = 'MT' or code.Code = 'CK') and client.Status = 1";
        DataTable dt = clientManager.GetClientList(sqlStr, null);
        ddlWhouse.DataSource = dt;
        ddlWhouse.DataTextField = ("en".Equals(language) ? "ENGShortName" : ("zh-hk".Equals(language) ? "HKShortName" : "CNShortName"));
        ddlWhouse.DataValueField = "PKID";
        ddlWhouse.DataBind();
        ddlWhouse.Items.Insert(0, new ListItem("select...", "0"));
    }


    /// <summary>
    /// 处理传入参数。。返回SQL条件和sqlparameter
    /// </summary>
    /// <param name="sqlstr"></param>
    /// <param name="parms"></param>
    private void ProcessParms(ref string sqlstr, ref SqlParameter[] parms)
    {
        List<SqlParameter> list = new List<SqlParameter>();
        sqlstr = "";

        if (ViewState["Shipper"] != null)
        {
            sqlstr += " and (dtl.ShipperID in (" + ViewState["Shipper"] + ")) ";
        }
        if (ViewState["Whouse"] != null)
        {
            list.Add(new SqlParameter("@Whouse", ViewState["Whouse"].ToString()));
            sqlstr += " and dtl.WhouseID = @Whouse";
        }
        if (ViewState["WinStart"] != null)
        {
            list.Add(new SqlParameter("@WinStart", ViewState["WinStart"].ToString()));
            sqlstr += " and dtl.WinStart = @WinStart";
        }
        if (ViewState["WinClose"] != null)
        {
            list.Add(new SqlParameter("@WinClose", ViewState["WinClose"].ToString()));
            sqlstr += " and dtl.WinClose = @WinClose";
        }

        list.Add(new SqlParameter("@VendorID", Session["LoginUserClientID"].ToString()));
        list.Add(new SqlParameter("@UserID", Session["UserID"].ToString()));
        parms = list.ToArray();
    }

    private void dataBind()
    {
        string sqlStr = @"SELECT booking.PKID as BID,dtl.*,client.CNShortName as Whouse, client.HKShortName as HKWhouse, 
                            client.ENGShortName as ENGWhouse, shipper.CNShortName as Shipper,
                            shipper.HKShortName as HKShipper, shipper.ENGShortName as ENGShipper
                        FROM BN_Booking booking inner join 
                            BN_BookingDtl dtl on booking.PKID = dtl.BookingID LEFT JOIN
                            Sy_Client client ON dtl.WhouseID = client.PKID LEFT JOIN
                            Sy_Client shipper ON dtl.ShipperID = shipper.PKID INNER JOIN
                            BN_BookingNoteDtl bnDtl ON dtl.BookingNoteDtlID = bnDtl.PKID INNER JOIN
                            Sy_ClientLinkMan linkman ON bnDtl.VendorLinkMan = linkman.PKID INNER JOIN
                            Users u ON linkman.LinkMan = u.UserName
                        WHERE booking.VendorID = @VendorID and u.UserID = @UserID and 
                              (dtl.JobDate IS NULL or dtl.JobDate = '') ";
        SqlParameter[] parms = null;
        string clause = string.Empty;
        ProcessParms(ref clause, ref parms);
        sqlStr += clause;

        DataTable dt = bookingManager.GetList(sqlStr, parms);
        DataView view = dt.DefaultView;
        view.Sort = ViewState["OrderBy"] + " " + ViewState["Accending"];
        gvPendingList.DataSource = view;
        gvPendingList.DataBind();
        if (dt != null && dt.Rows.Count > 0)
        {
            lblTotal.Text = dt.Rows.Count.ToString();
        }
        else
        {
            lblTotal.Text = "0";
        }
    }

    protected void gvPendingList_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvPendingList.PageIndex = e.NewPageIndex;
        dataBind();

    }
    protected void gvPendingList_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        dataBind();

    }
    protected void gvPendingList_Sorting(object sender, GridViewSortEventArgs e)
    {
        if (e.SortExpression.ToLower() == ViewState["OrderBy"].ToString().ToLower())
        {
            if (ViewState["Accending"].ToString().ToLower() == "asc")
            {
                ViewState["Accending"] = "desc";
            }
            else
            {
                ViewState["Accending"] = "asc";
            }
        }
        else
        {
            ViewState["OrderBy"] = e.SortExpression;
        }

        dataBind();
    }

    protected void btnSearch_Click(object sender, EventArgs e)
    {
        if (lstSelShipper.Items.Count > 0)
        {
            string item = string.Empty;
            for (int i = 0; i < lstSelShipper.Items.Count; i++)
            {
                item += lstSelShipper.Items[i].Value + ",";
            }
            ViewState["Shipper"] = item.Substring(0, item.Length - 1);
        }
        else
        {
            ViewState["Shipper"] = null;
        }
        if (ddlWhouse.SelectedValue != "0")
        {
            ViewState["Whouse"] = ddlWhouse.SelectedValue;
        }
        else
        {
            ViewState["Whouse"] = null;
        }
        if (txtWinStart.Text != null && txtWinStart.Text.Trim() != "")
        {
            try
            {
                DateTime.Parse(txtWinStart.Text.Trim());
                ViewState["WinStart"] = txtWinStart.Text.Trim();
            }
            catch { ViewState["WinStart"] = null; }
        }
        else
        {
            ViewState["WinStart"] = null;
        }
        if (txtWinClose.Text != null && txtWinClose.Text.Trim() != "")
        {
            try
            {
                DateTime.Parse(txtWinClose.Text.Trim());
                ViewState["WinClose"] = txtWinClose.Text.Trim();
            }
            catch { ViewState["Winclose"] = null; }
        }
        else
        {
            ViewState["WinClose"] = null;
        }
        
        dataBind();
    }

    protected void ddlPages_SelectedIndexChanged(object sender, EventArgs e)
    {
        gvPendingList.PageSize = int.Parse(ddlPages.SelectedValue);
        dataBind();
    }
    protected void gvPendingList_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Label lblShipper = (Label)e.Row.FindControl("lblShipper");
            Label lblHKShipper = (Label)e.Row.FindControl("lblHKShipper");
            Label lblENGShipper = (Label)e.Row.FindControl("lblENGShipper");

            Label lblWhouse = (Label)e.Row.FindControl("lblWhouse");
            Label lblHKWhouse = (Label)e.Row.FindControl("lblHKWhouse");
            Label lblENGWhouse = (Label)e.Row.FindControl("lblENGWhouse");

            if ("en".Equals(language))
            {
                lblShipper.Visible = false;
                lblHKShipper.Visible = false;
                lblENGShipper.Visible = true;

                lblWhouse.Visible = false;
                lblHKWhouse.Visible = false;
                lblENGWhouse.Visible = true;
            }
            else if ("zh-hk".Equals(language))
            {
                lblShipper.Visible = false;
                lblHKShipper.Visible = true;
                lblENGShipper.Visible = false;

                lblWhouse.Visible = false;
                lblHKWhouse.Visible = true;
                lblENGWhouse.Visible = false;
            }
            else
            {
                lblShipper.Visible = true;
                lblHKShipper.Visible = false;
                lblENGShipper.Visible = false;

                lblWhouse.Visible = true;
                lblHKWhouse.Visible = false;
                lblENGWhouse.Visible = false;
            }
        }
    }


    protected void lbtnGo_Click(object sender, EventArgs e)
    {
        TextBox txtPages = ((TextBox)gvPendingList.BottomPagerRow.FindControl("txtPages"));
        try
        {
            int i = Convert.ToInt32(txtPages.Text) - 1;
            if (i >= 0 && i < gvPendingList.PageCount)
            {
                this.gvPendingList.PageIndex = i;
                //数据绑定
                dataBind();
            }
            else
            {
                Jscript.AlertInAjax(Resources.Messages.WrongPageNumInput, UpdatePanel1);
                return;
            }
        }
        catch
        {
            Jscript.AlertInAjax(Resources.Messages.WrongPageNumInput, UpdatePanel1);
        }
    }


    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (Request["chkSelected"] != null)
        {
            bool isDateTime = false;
            Regex reg = new Regex("((1[89]\\d{2})|([2-8]\\d{3}))[-](([1][012])|(0{1}[1-9]))[-]((3[01])|([12]\\d)|(0{1}[1-9]))");
            isDateTime = reg.IsMatch(txtNewJobDate.Text.Trim());
            reg = new Regex("(([0][0-9])|([1][0-9])|([2][0-3]))([0-5][0-9])");
            string h = txtNewJobDateH.Text.Trim();
            h = h.Replace(":", "");
            isDateTime = isDateTime && reg.IsMatch(h);

            if (isDateTime)
            {
                string jobDate = txtNewJobDate.Text.Trim() + StringUtil.GetTime(txtNewJobDateH.Text.Trim());
                string[] dtlIds = Request["chkSelected"].ToString().Split(',');
                string userName = Session["UserName"].ToString();
                object userId = Session["UserID"];
                foreach (string dtlId in dtlIds)
                {
                    string sql = "update bn_bookingnotedtl set status=@Status where pkid=(select bookingnotedtlid from bn_bookingdtl where pkid=@PKID)";
                    SqlParameter[] parms = new SqlParameter[2];
                    parms[0] = new SqlParameter("@Status", HK2009.Common.Enums.BookingNoteDtlStatus.BOOKING.ToString("d"));
                    parms[1] = new SqlParameter("@PKID", dtlId);
                    bookingManager.UpdateBookingStatus(sql, parms);
                    if (!bookingManager.UpdateDetail(int.Parse(dtlId), jobDate, userName, userId, false))
                    {
                        Jscript.AlertInAjax(Resources.Messages.UpdateFailed, UpdatePanel1);
                        return;
                    }
                }
            }
            else
            {
                Jscript.AlertInAjax(Resources.Messages.WrongDateTimeFormat, UpdatePanel1);
            }
            dataBind();
        }
    }

    protected void btnAddSShipper_Click(object sender, EventArgs e)
    {
        if (lstShipper.SelectedValue != string.Empty)
        {
            for (int i = 0; i < lstShipper.Items.Count; i++)
            {
                bool issel = false;
                if (lstShipper.Items[i].Selected)
                {
                    for (int j = 0; j < lstSelShipper.Items.Count; j++)
                    {
                        if (lstShipper.Items[i].Value == lstSelShipper.Items[j].Value)
                        {
                            issel = true;
                            break;
                        }
                    }

                    if (!issel)
                    {
                        ListItem item = new ListItem();
                        item.Text = lstShipper.Items[i].Text;
                        item.Value = lstShipper.Items[i].Value;
                        lstSelShipper.Items.Add(item);
                    }
                }
            }
        }
        else
        {

        }

    }
    protected void btnDeleteSShipper_Click(object sender, EventArgs e)
    {
        if (lstSelShipper.Items.Count > 0)
        {
            ListItemCollection lstColl = new ListItemCollection();
            for (int i = 0; i < lstSelShipper.Items.Count; i++)
            {
                if (!lstSelShipper.Items[i].Selected)
                {
                    ListItem item = new ListItem(lstSelShipper.Items[i].Text, lstSelShipper.Items[i].Value);
                    lstColl.Add(item);
                }
            }
            if (lstColl != null && lstColl.Count > 0)
            {
                lstSelShipper.Items.Clear();
                for (int j = 0; j < lstColl.Count; j++)
                {
                    lstSelShipper.Items.Add(lstColl[j]);
                }
            }
            else
            {
                lstSelShipper.Items.Clear();
            }

        }
    }

}
